package main

import( 
	   "fmt"
       "os"
       "strings" 
	   "bufio"
	   "io"
	)

var count int = 0

var pattern []string

func isPattern(filename string) bool{
	for _,v := range pattern {
		if(strings.Contains(filename,v)){
			return true
		}
	}
	return false
}

func isVaildLine(line string) bool {
	if(len(line) > 2){
		return true
	}
	if(len(line) == 1){
		return false
	}
	if(len(line) == 2 && line[0] == '\r'){
		return false
	}
	return true
}

func process_regfile(filename string){
	if(isPattern(filename)){
		f,err := os.Open(filename)
		if err != nil {
			fmt.Printf("file %s open error\n",filename)
			return
		}
		bufferReader := bufio.NewReader(f)
		eof := false
		for !eof {
			line,err := bufferReader.ReadString('\n')
			if err == io.EOF{
				err = nil
				eof = true
			}else if err != nil{
				fmt.Printf("parse file error\n")
				f.Close()
				return
			}
			if(isVaildLine(line)){
				count++
			}

		}
		f.Close()		
		
	}
}

func trvaldir(dir string){
	f,err := os.Open(dir)
	if(dir != "./"){ 
		os.Chdir(dir)
	}
	if err != nil {
		fmt.Printf("open cur dir error\n")
		return
	}
	var fi []os.FileInfo
	fi,err = f.Readdir(0)
	for _,v := range fi{
		if(v.IsDir()){
			trvaldir(v.Name())	
		}else if(v.Mode().IsRegular()){
			process_regfile(v.Name())
		}
	}
	//go back to parentdir
	os.Chdir("../")
	f.Close()
}

func main(){
	if len(os.Args) < 2 {
		return
	}
	for k,v := range os.Args {
		if k > 0 { 
			pattern = append(pattern,v)
		}
	}
	trvaldir("./")
	fmt.Printf("totalline:%d\n",count)
	var b []byte = make([]byte, 1)
	os.Stdin.Read(b)
}
